import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../index.dart';

class ChatService extends GetxService {
  static ChatService get to => Get.find();
  final _storage = Storage();

  // 获取所有聊天数据
  Future<List<ChatModel>> get_chats() async {
    final isInit = _storage.get_bool(Constants.is_init_chat_data);
    if (isInit != true) {
      await _init_chat_data();
    }

    final chat_json = _storage.get_json(Constants.chat_data);
    if (chat_json == null) {
      return [];
    }

    try {
      Map<String, dynamic> chat_map = chat_json;

      return chat_map.values
          .expand(
            (chats) => (chats as List).map((chat) => ChatModel.fromJson(chat)),
          )
          .toList();
    } catch (e) {
      return [];
    }
  }

  // 获取两个用户间的聊天记录
  Future<List<ChatModel>> get_chats_between_users(
    String user_id1,
    String user_id2,
  ) async {
    final allChats = await get_chats();
    return allChats
        .where(
          (chat) =>
              (chat.spend_user_id == user_id1 &&
                  chat.receive_user_id == user_id2) ||
              (chat.spend_user_id == user_id2 &&
                  chat.receive_user_id == user_id1),
        )
        .toList();
  }

  // 发送新消息
  Future<bool> send_message(ChatModel message) async {
    try {
      final all_chats = await get_chats();
      all_chats.add(message);

      Map<String, List<Map<String, dynamic>>> grouped_chats = {};

      for (var chat in all_chats) {
        if (!grouped_chats.containsKey(chat.spend_user_id)) {
          grouped_chats[chat.spend_user_id] = [];
        }
        grouped_chats[chat.spend_user_id]!.add(chat.toJson());
      }

      await _storage.set_json(Constants.chat_data, grouped_chats);

      return true;
    } catch (e) {
      return false;
    }
  }

  // 将与特定用户的所有消息标记为已读
  Future<bool> mark_all_as_read(
    String current_user_id,
    String other_user_id,
  ) async {
    try {
      final all_chats = await get_chats();
      bool updated = false;

      for (int i = 0; i < all_chats.length; i++) {
        var chat = all_chats[i];
        if (chat.spend_user_id == other_user_id &&
            chat.receive_user_id == current_user_id &&
            !chat.is_reading) {
          var updatedChat = ChatModel(
            chat_id: chat.chat_id,
            detail: chat.detail,
            spend_user_id: chat.spend_user_id,
            receive_user_id: chat.receive_user_id,
            created_time: chat.created_time,
            is_reading: true,
          );
          all_chats[i] = updatedChat;
          updated = true;
        }
      }

      if (!updated) {
        return true;
      }

      Map<String, List<Map<String, dynamic>>> grouped_chats = {};

      for (var chat in all_chats) {
        String key = chat.spend_user_id;
        if (!grouped_chats.containsKey(key)) {
          grouped_chats[key] = [];
        }
        grouped_chats[key]!.add(chat.toJson());
      }

      await _storage.set_json(Constants.chat_data, grouped_chats);

      return true;
    } catch (e) {
      return false;
    }
  }

  // 初始化聊天数据
  Future<void> _init_chat_data() async {
    try {
      Map<String, List<Map<String, dynamic>>> chat_data_json = {};

      chat_data.forEach((user_id, chats) {
        chat_data_json[user_id] = chats.map((chat) => chat.toJson()).toList();
      });

      await _storage.set_json(Constants.chat_data, chat_data_json);
      await _storage.set_bool(Constants.is_init_chat_data, true);
    } catch (e) {
      debugPrint('初始化聊天数据失败: $e');
      // 初始化失败
    }
  }

  // 隐藏历史聊天记录
  Future<bool> hide_previous_chats_for_current_user(
    String current_user_id,
    String other_user_id,
  ) async {
    try {
      final now = DateTime.now().toIso8601String();
      final hideTimeKey =
          "${Constants.hidden_chat_time}_${current_user_id}_$other_user_id";
      await _storage.set_string(hideTimeKey, now);
      return true;
    } catch (e) {
      return false;
    }
  }

  // 获取用户所有可见会话
  Future<Map<String, List<ChatModel>>> get_all_user_visible_chats(
    String user_id,
  ) async {
    final all_chats = await get_chats();
    Map<String, List<ChatModel>> result = {};

    // 获取用户的聊天记录
    final user_chats = all_chats
        .where(
          (chat) =>
              chat.spend_user_id == user_id || chat.receive_user_id == user_id,
        )
        .toList();
    final Set<String> chat_user_ids = user_chats
        .map(
          (chat) => chat.spend_user_id == user_id
              ? chat.receive_user_id
              : chat.spend_user_id,
        )
        .toSet();

    final hidden_chats_key = "${Constants.hidden_chats}_$user_id";
    List<String> hidden_users = _storage.get_list(hidden_chats_key);

    // 遍历所有聊天用户
    chat_user_ids.forEach((other_user_id) {
      if (hidden_users.contains(other_user_id)) {
        return; // 跳过隐藏的用户
      }

      final hide_time_key =
          "${Constants.hidden_chat_time}_${user_id}_$other_user_id";
      String? hide_time_str = _storage.get_string(hide_time_key);

      final conversation_chats = user_chats
          .where(
            (chat) =>
                (chat.spend_user_id == user_id &&
                    chat.receive_user_id == other_user_id) ||
                (chat.spend_user_id == other_user_id &&
                    chat.receive_user_id == user_id),
          )
          .toList();

      if (hide_time_str != null) {
        final hide_time = DateTime.parse(hide_time_str);
        final visible_chats = conversation_chats.where((chat) {
          final chat_time = DateTime.parse(chat.created_time);
          return chat_time.isAfter(hide_time);
        }).toList();

        if (visible_chats.isNotEmpty) {
          result[other_user_id] = visible_chats;
        }
      } else {
        result[other_user_id] = conversation_chats;
      }
    });

    return result;
  }

  // 获取两个用户间的可见聊天
  Future<List<ChatModel>> get_visible_chats_between_users(
    String current_user_id,
    String other_user_id,
  ) async {
    final hiddenChatsKey = "${Constants.hidden_chats}_$current_user_id";
    List<String> hidden_users = _storage.get_list(hiddenChatsKey);

    if (hidden_users.contains(other_user_id)) {
      return [];
    }

    final hide_time_key =
        "${Constants.hidden_chat_time}_${current_user_id}_$other_user_id";
    String? hide_time_str = _storage.get_string(hide_time_key);

    final all_chats = await get_chats_between_users(
      current_user_id,
      other_user_id,
    );

    if (hide_time_str != null) {
      final hide_time = DateTime.parse(hide_time_str);
      return all_chats.where((chat) {
        final chat_time = DateTime.parse(chat.created_time);
        return chat_time.isAfter(hide_time);
      }).toList();
    }

    return all_chats;
  }
}
